package com.dormitoryAdministratorSystem.dao.maintain.impl;

import com.dormitoryAdministratorSystem.dao.maintain.IMaintainDao;
import com.dormitoryAdministratorSystem.entity.maintain.Maintain;
import com.dormitoryAdministratorSystem.entity.room.RoomBean;
import com.dormitoryAdministratorSystem.util.DBUtil;
import com.sun.org.apache.regexp.internal.RE;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MaintainDaoImpl implements IMaintainDao {
    @Override
    public List<Maintain> getMainByRoomId(int rId) {
        List<Maintain> list = new ArrayList<>();

        String sql = "select mid, rid, damage, reportTime, isSolve from t_maintain where rId = ? ";
        ResultSet rSet = DBUtil.excuteQuery(sql,rId);

        try {
            while(rSet.next()){
                list.add(getMaintain(rSet));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.close();
        }

        return list;
    }

    @Override
    public int insertMaintain(Maintain m) {
        String sql = "insert into t_maintain values(null, ?, ?, ?, ?)";
        int result = DBUtil.excuteUpdate(
                sql,
                m.getRoomBean().getRId(),
                m.getDamage(),
                m.getReportTime(),
                m.getIsSolve()
        );
        return result;
    }

    @Override
    public int updateMaintain(Maintain m) {
        String sql = "update t_maintain set isSolve = ? where mid = ?";
        return DBUtil.excuteUpdate(
                sql,
                m.getIsSolve(),
                m.getMId()
        );
    }

    @Override
    public Maintain getMaintainInfo(int mId) {
        Maintain m = null;

        String sql = "select mid, rid, damage, reportTime, isSolve from t_maintain where mid = ?";
        ResultSet rSet = DBUtil.excuteQuery(sql,mId);

        try {
            while(rSet.next()){
                m = getMaintain(rSet);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.close();
        }

        return m;
    }

    private Maintain getMaintain(ResultSet rSet) throws SQLException {
        Maintain m = new Maintain();
        m.setMId(rSet.getInt("mid"));
        m.setDamage(rSet.getString("damage"));
        m.setReportTime(rSet.getDate("reportTime"));
        m.setIsSolve(rSet.getString("isSolve"));
        RoomBean r = new RoomBean();
        r.setRId(rSet.getInt("rid"));
        m.setRoomBean(r);

        return m;
    }
}
